package com.mk.security.distributed.uaa.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
//方法授权,默认是关闭的,加了这个，在再其他方法上添加相应的注解就可以跨越过滤器 进行访问
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //认证管理器
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    //密码编码器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //认证控制
    //安全拦截机制（最重要）
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/order/**").hasAnyAuthority("p1")
                .antMatchers("/login*").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin();
    }

    //安全拦截机制
//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        //默认csrf是开启的
//        http.csrf().disable()
////                http
//                .authorizeRequests()
//                .antMatchers("/login/test1").hasAuthority("p1")//访问权限
//                .antMatchers("/login/test2").hasAuthority("p2")//设置访问权限
//                .antMatchers("/login/**").authenticated()//除了login/**的路径都要认证
//                .anyRequest().permitAll()
//                .and()
//                .formLogin()//允许表单登录
////                .loginPage("/login-view")//登录页面
//                .loginProcessingUrl("/loginTest")//登录处理url,jsp里面的action=login
//                .successForwardUrl("/login/")//登录成功后请求的url路径
//                .and()
//                //会话控制，设置是否需要session
//                .sessionManagement()
//                .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
//                .and()
//                .logout()
//                //自定义url路径
//                .logoutUrl("/logout")
//                //成功退出后请求的url路径是  登录的url请求路径
//                //退出时会自动使HTTP Session失效，清楚SecurityContextHolder，并且跳转到/login界面
//                .logoutSuccessUrl("/login?logout");
//        }
}
